<?php

/**
 * @Author: user
 * @Date:   2019-03-05 10:48:44
 * @Last Modified by:   user
 * @Last Modified time: 2019-03-05 11:04:19
 */
/**
 * 子系统接口加密api
 */
namespace app\api\controller;
use think\Controller;
use think\Db;
use app\api\model\ApiCommonModel;

/**
 * 子系统接口加密api控制器类
 */
class ApiAccessEncodeController extends Controller
{

    private $accessTokenURL = "/api/api_access_authority/accessToken?";  // 获取access_token
    private $jsapiTicketURL = "/api/api_access_authority/getToken?";  // 获取临时票据
    private $signVerifyURL = "/api/api_access_authority/signVerifyTest?";    // 测试签名是否正确


    protected function _initialize()
    {

    }


    /**
     * 1、获取access_token
     *
     * token需要进行存储
     */
    public function accessToken( $userInfo ) 
    {
		//dump($userInfo);
        // 判断 session 中是否存在access_token：如果存在那么就输出。如果没有那么就通过接口获取，然后进行存储
		//session('?access_token',null);
		//dump(session('?access_token'));exit;
        if(session('?access_token')){
            $access_token = session('access_token');
            return $access_token;
        }else{
            $appid = $userInfo['appid'];
            $appsecret = $userInfo['appsecret'];
            $urlData = cmf_curl_get($this->assemblyUrl( $userInfo[ 'addr' ],$this->accessTokenURL)."&appid=$appid&appsecret=$appsecret");
            $info = json_decode($urlData,true);
            if($info['status']=='error'){
                throw new \Exception('ERROR:'.$info['message'], 1);
            }
            $result = $info['data']['access_token'];
            // 先写入到 session 中,在返回数据
            session('access_token',$result);
            return $result;            
        }
    }

    /**
     * 2、获取临时票据jwt token
     *
     * token需要进行存储
     */
    public function jsapiTicket( $userInfo )
    {
        // 获取帐号token
        $accessToken = $this->accessToken( $userInfo );


        //$jsapi_ticket = session('jsapi_ticket');    // jsapi_ticket
        //$expires_in = session('expires_in');    // expires_in

        if( !empty($jsapi_ticket) && $expires_in>time() ){
            return $jsapi_ticket;
        }else{
            // 配置个人信息 
            $user = base64_encode($userInfo['user_login'].",".$userInfo['user_pass']);

            $urlData = cmf_curl_get( $this->assemblyUrl( $userInfo [ 'addr' ], $this->jsapiTicketURL)."&sub=".$user."&jti=".$accessToken);

            $info = json_decode($urlData,true);
            if($info['status']=='error'){
                throw new \Exception('ERROR:'.$info['message'], 1);
            }

            // 先获取，在写入
            $jsapi_ticket = $info['data']['jsapi_ticket'];
            $expires_in = $info['data']['expires_in'];

            // 先写入到 session 中,在返回数据
			
            session('jsapi_ticket',$jsapi_ticket);
            session('expires_in',$expires_in);

            return $jsapi_ticket;
        }
    }



    /**
     * 3、签名加解密
     *
     * @return 签名+数据
     */
    public function signCode($data=array())
    {   
			//session('?access_token',null);
			//session('jsapi_ticket',null);exit;
		 $userInfo = $this->getUserInfo( $data['cid'] );
		$data['appid'] = $userInfo['appid'];
        $data['timestamp'] = time();
        $data['noncestr'] = cmsrandom(8,'all');
        $data['jsapi_ticket'] = $this->jsapiTicket( $userInfo );
        $Generatesign = new \sign\Generatesign();
        $signature = $Generatesign->signature($data);
        if($signature['status']=='error'){
            throw new \Exception('ERROR:'.$signature['message'], 1);
        }
        $data['signture']=$signature['data']['sign'];
        // $paramString = http_build_query($data);
        return $data;
    }

    /**
     * 获取用户信息
     */
    private function getUserInfo( $cid )
    {
        $company = Db::name('company')->where('id' , $cid)->find();
        $role = Db::name('role')->where('company_id' , $cid ) -> where( 'parent_id' , 1 ) ->find();
        $userId = Db::name('user_attach')->where('company_id',$cid)->where('role_id',$role['id'])->value('user_id');
        $user = Db::name('user')->where('id',$userId)->field("user_login,user_pass")->find();
        $user['company_id'] = $cid;
        $user['appid'] = str_replace("===","",$company['aid']);
        $user['key'] = md5($company['id'].$company['create_time']);
        $user['appsecret']= md5(md5($cid.$user['appid'].$user['key'].$company['create_time']) );
        $user['addr'] = $company['commicate_addr'];
        return $user;
    }

    /**
     * 合成url
     */
    private function assemblyUrl( $url , $api )
    {
        return $url.$api;
    }


}
